#include "app_message.h"
// 将数组数据转为16进制字符串

// 将数组转换为JSON格式
char *app_message_ArrayTocJson(char *msg, int len)
{
    int connect_type = msg[0];
    int id_len = msg[1];
    int msg_len = msg[2];

    // id数组
    char id[id_len + 1];
    memcpy(id, msg + 3, id_len);
    
    // 消息数组
    char msg_array[msg_len + 1];

    memcpy(msg_array, msg + 3 + id_len, msg_len);
 
    // 将数组转为16进制字符串
    char *id_hex = app_message_ArrayToHex(id, id_len);

    char *msg_hex = app_message_ArrayToHex(msg_array, msg_len);

    // 封装json
    cJSON *cjson = cJSON_CreateObject();
    cJSON_AddNumberToObject(cjson, "connect_type", connect_type);
    cJSON_AddStringToObject(cjson, "ID", id_hex);
    cJSON_AddStringToObject(cjson, "msg", msg_hex);
    // 将json转为字符串
    char *json = cJSON_PrintUnformatted(cjson);

    cJSON_Delete(cjson);
    free(id_hex);
    free(msg_hex);
    return json;
}

// 将json转为数组
int app_message_JsonToCharArray(char *json, char *array, int len)
{
    // 解析json
    cJSON *cjson = cJSON_Parse(json);
    if (cjson == NULL)
    {
        log_error("json解析失败");
        return -1;
    }
    // 获取connect_type
    int connect_type = cJSON_GetObjectItem(cjson, "connect_type")->valueint;
    
    // 获取id
    char *id_hex = cJSON_GetObjectItem(cjson, "ID")->valuestring;

    // 获取msg
    char *msg_hex = cJSON_GetObjectItem(cjson, "msg")->valuestring;

    // 将16进制字符串转为数组
    int id_len = strlen(id_hex);
    int msg_len = strlen(msg_hex);
    char *id = app_message_HexToArray(id_hex, id_len);

    char *msg = app_message_HexToArray(msg_hex, msg_len);

    int data_len = 3 + id_len / 2 + msg_len / 2;
    if (data_len > len)
    {
        log_error("数组长度不够");
        return -1;
    }
    // 封装数组
    array[0] = connect_type;
    array[1] = id_len / 2;
    array[2] = msg_len / 2;
    memcpy(array + 3, id, id_len / 2);
    memcpy(array + 3 + (id_len / 2), msg, msg_len / 2);

    cJSON_Delete(cjson);
    free(id);
    free(msg);

    return data_len;
}